<template>
  <div>
    <el-card class="box-card" style="margin: 22px auto">
      <div slot="header" class="clearfix">
        <span>我的资料</span><br>
<!--        <el-button style="float: right; padding: 3px 0" type="text">修改</el-button>-->
<!--        <el-button type="text" @click="getAddress">收货地址</el-button>-->
        <router-link class="list-group-item" active-class="active" to="/PersonCenter/getAddress">收货地址</router-link>
        <el-button type="text" @click="dialogFormVisible = true" style="margin-left: 20em;">修改个人信息</el-button>
<!--        <el-button @click="upImg">上传头像</el-button>-->
      </div>
      <div>

        <el-form ref="form" :model="infoList" label-width="80px">
          <el-form-item label="用户名">
            <el-input v-model="infoList.username" disabled></el-input>
          </el-form-item>
          <el-form-item label="个人头像">
            <el-image
                style="width: 100px; height: 100px"
                :src="form.headImg"></el-image>
          </el-form-item>
          <el-form-item label="我的昵称">
            <el-input v-model="infoList.nickName" disabled></el-input>
          </el-form-item>
          <el-form-item label="手机号码">
            <el-input v-model="infoList.tel" disabled></el-input>
          </el-form-item>
          <el-form-item label="我的邮箱">
            <el-input v-model="infoList.email" disabled></el-input>
          </el-form-item>
<!--          <el-form-item label="创建时间">-->
<!--            <el-input v-model="infoList.created_time" disabled></el-input>-->
<!--          </el-form-item>-->
<!--          <el-form-item label="修改时间">-->
<!--            <el-input v-model="infoList.updated_time" disabled></el-input>-->
<!--          </el-form-item>-->
        </el-form>
      </div>
    </el-card>
    <el-dialog title="个人信息" :visible.sync="dialogFormVisible">
      <el-form :model="form" :rules="rules" ref="form">
        <el-form-item label="用户名" :label-width="formLabelWidth" prop="username">
          <el-input v-model="form.username" autocomplete="off" disabled></el-input>
        </el-form-item>
        <el-form-item label="账号头像" style="margin-left: 54px;">
          <el-upload
              class="avatar-uploader"
              action="http://wlgc5.oss-cn-shanghai.aliyuncs.com"
              :show-file-list="false"
              :data="dataObj"
              :on-success="handleUploadSuccess"
              :before-upload="beforeUpload">
            <img v-if="form.headImg" :src="form.headImg" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="我的手机" :label-width="formLabelWidth" prop="phone">
          <el-input v-model="form.phone" autocomplete="off" disabled></el-input>
        </el-form-item>
        <el-form-item label="我的邮箱" :label-width="formLabelWidth" prop="email">
          <el-input v-model="form.email" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="我的昵称" :label-width="formLabelWidth" prop="nickName">
          <el-input v-model="form.nickName" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="updatedInfo('form')">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "PersonInfo",
  data(){
    var checkEmail = (rule, value, callback) => {
      const mailReg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/
      if (!value) {
        return callback(new Error('邮箱不能为空'))
      }
      setTimeout(() => {
        if (mailReg.test(value)) {
          callback()
        } else {
          callback(new Error('请输入正确的邮箱格式'))
        }
      }, 100)
    }
    var checkNickName = (rule, value, callback) => {
      const NickNameReg = /[^]*/
      if (!value) {
        return callback(new Error('昵称不能为空'))
      }
      setTimeout(() => {
        if (NickNameReg.test(value)) {
          callback()
        } else {
          callback(new Error('昵称格式不对。'))
        }
      }, 100)
    }
    return{
      infoList:{},
      dialogFormVisible: false,
      userId:null,
      form: {
        username:'',
        email:'',
        nickName:'',
        //用户头像
        headImg:'',
        phone:''
      },
      dataObj:{},
      formLabelWidth: '120px',
      // imageUrl: ''
      rules:{
        email: [{ validator: checkEmail, trigger: 'blur' }],
        nickName: [{ validator: checkNickName, trigger: 'blur' },{ min: 1, max: 15, message: '长度在 1 到 15 个字符', trigger: 'blur' }],
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 30, message: '长度在 3 到 30 个字符', trigger: 'blur' }
        ]
      }

    }
  },
  created() {
    // let username = window.sessionStorage.getItem('username')
    this.getRequest('/cms/user/info').then((resp)=>{
      console.log(resp)
      this.infoList = resp.data
      this.form.email = resp.data.email
      this.form.nickName = resp.data.nickName
      this.form.username = resp.data.username
      this.form.headImg = resp.data.headImg
      this.form.phone = resp.data.tel
      this.userId = resp.data.id
    })
  },
  methods:{
    handleAvatarSuccess(res, file) {
      this.form.imageUrl = URL.createObjectURL(file.raw);
      this.postRequest('/uploadImg',this.form.imageUrl).then((resp)=>{
          if(resp.status==200){
            this.$message.success('上传成功。')
          }else{
            this.$message.success('上传失败。')
          }
      })
    },
    beforeUpload(file) {
      const isImg = file.type === 'image/jpeg';
      const fileSuffix = file.name.substring(file.name.lastIndexOf(".") + 1);

      const whiteList = ["png", "jpeg", "jpg"];

      if (whiteList.indexOf(fileSuffix) === -1) {
        this.$msg("上传文件只能是" + whiteList.join(',') + "格式", "error");
        return false;
      }

      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isImg) {
        this.$message.error('上传头像图片只能是 JPG|PNG|JPEG 格式!');
        return false;
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
        return false;
      }

      let _self = this;

      return new Promise((resolve, reject) => {
        this.getRequest('/aliyun/oss/policy').then(response => {
          _self.dataObj.policy = response.data.policy;
          _self.dataObj.signature = response.data.signature;
          _self.dataObj.ossaccessKeyId = response.data.accessKeyId;
          _self.dataObj.key = response.data.dir + '/${filename}';
          _self.dataObj.dir = response.data.dir;
          _self.dataObj.host = response.data.host;
          // _self.dataObj.callback = response.data.callback;
          resolve(true)
        }).catch(err => {
          console.log(err)
          reject(false)
        })
      })
    },
    handleUploadSuccess(res, file) {
      console.log(res)
      let url = this.dataObj.host + '/' + this.dataObj.dir + '/' + file.name;
      this.form.headImg = url
    },
    updatedInfo(form){
      this.$refs[form].validate((valid)=>{
        if(valid){
          this.postRequest(`/cms/user/update/${this.userId}` ,this.form).then((resp)=>{
            console.log(resp)
            if(resp.status===200){
              this.$message.success('修改成功')
              this.dialogFormVisible = false
              this.$message.success(resp.message)
              location.reload()
            }else{
              this.$message.error(resp.message)
              this.dialogFormVisible = false
              location.reload()
            }
          })
        }else{
          this.$message.success('信息填写不完整。')
        }
      })

    },

    getAddress(){
      this.$router.push({path:'/getAddress'})
    }
  }
}
</script>

<style scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.text {
  font-size: 14px;
}

.item {
  margin-bottom: 18px;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}
.clearfix:after {
  clear: both
}

.box-card {
  width: 480px;
}
</style>